package org.example.myleet.p676;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class MagicDictionary2 {

    private Set<String> wordSet;

    public MagicDictionary2() {
        wordSet = new HashSet<>();
    }

    public void buildDict(String[] dictionary) {
        wordSet.addAll(Arrays.asList(dictionary));
    }

    public boolean search(String searchWord) {
        //暴力匹配，对searchWord的每一个位置尝试替换字母并在wordSet中匹配
        for (int i = 0; i < searchWord.length(); ++i) {
            char c = searchWord.charAt(i);
            String prefix = searchWord.substring(0, i);
            String suffix = searchWord.substring(i + 1);
            for (int j = 0; j < 26; ++j) {
                char cNew = (char) (j + 'a');
                if (c == cNew) {
                    continue;
                }
                String newWord = prefix + cNew + suffix;
                if (wordSet.contains(newWord)) {
                    return true;
                }
            }
        }
        return false;
    }
}
